<template>
  <div class="account-box">
    <!-- 登录方式切换 -->
    <div class="toggle">
      <a href="javascript:;" @click="isMsgLogin = false" v-if="isMsgLogin">
        <i class="iconfont icon-user"></i>
        使用账号登录
      </a>
      <a href="javascript:;" @click="isMsgLogin = true" v-else>
        <i class="iconfont icon-msg"></i>
        使用短信登录
      </a>
    </div>
    <Form ref="target" :validation-schema="schema" v-slot="{ errors }">
      <div class="form">
        <!-- 使用账号密码登录 -->
        <!--
    ref: 引用；后边手动兜底校验要使用
    validation-schema： 用来指定校验规则(这里的规则)
    v-slot: 作用域插槽，如果校验失败，errors中会保存校验失    败的结果
      -->
        <!-- Field: v-model：双向绑定数据项
            name：指定要校验的字段
           :class="{error:errors.mobile}" 如果校验失败，就补充   error类
           动态绑定class用来约定错误发生时的样子  -->
        <template v-if="!isMsgLogin">
          <div class="form-item">
            <div class="input">
              <i class="iconfont icon-user"></i>
              <Field
                type="text"
                placeholder="请输入用户名"
                name="account"
                v-model="formData.account"
                :class="{ error: errors.account }"
              />
            </div>
            <div class="error" v-if="errors.account">
              <i class="iconfont icon-warning" />{{ errors.account }}
            </div>
          </div>
          <div class="form-item">
            <div class="input">
              <i class="iconfont icon-lock"></i>
              <Field
                type="password"
                placeholder="请输入密码"
                v-model="formData.password"
                name="password"
                :class="{ error: errors.password }"
              />
            </div>
            <div class="error" v-if="errors.password">
              <i class="iconfont icon-warning" />{{ errors.password }}
            </div>
          </div>
        </template>
        <!-- 使用手机验证码登录 -->
        <template v-else>
          <div class="form-item">
            <div class="input">
              <i class="iconfont icon-user"></i>
              <Field
                type="text"
                placeholder="请输入手机号"
                v-model="formData.mobile"
                name="mobile"
                :class="{ error: errors.mobile }"
              />
            </div>
            <div class="error" v-if="errors.mobile">
              <i class="iconfont icon-warning" />{{ errors.mobile }}
            </div>
          </div>
          <div class="form-item">
            <div class="input">
              <i class="iconfont icon-code"></i>
              <Field
                type="text"
                placeholder="请输入验证码"
                v-model="formData.code"
                name="code"
                :class="{ error: errors.code }"
              />
              <span class="code" @click="sendCode">{{
                time === 0 ? "发送验证码" : `${time}秒后重发`
              }}</span>
            </div>
            <div class="error" v-if="errors.code">
              <i class="iconfont icon-warning" />{{ errors.code }}
            </div>
          </div>
        </template>
        <div class="form-item">
          <div class="agree">
            <Field as="XtxCheckbox" v-model="formData.isAgree" name="isAgree" />
            <span>我已同意</span>
            <a href="javascript:;">《隐私条款》</a>
            <span>和</span>
            <a href="javascript:;">《服务条款》</a>
            <div class="error" v-if="errors.isAgree">
              <i class="iconfont icon-warning" />{{ errors.isAgree }}
            </div>
          </div>
        </div>
        <a href="javascript:;" class="btn" @click="checkForm">登录</a>
      </div>
    </Form>
    <!-- qq登录 -->
    <div class="action">
      <a
        href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback"
      >
        <img
          src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png"
          alt=""
        />
      </a>
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>
<script>
import { ref, reactive } from 'vue'
import { Form, Field } from 'vee-validate'
import Message from '@/components/Message.js'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { userMobileLoginMsg } from '@/api/user'
// 引入表单校验
import validateForm from '@/utils/validate'
// 引入封装倒计时函数
import { useCountDown } from '@/compositions/index'

export default {
  components: {
    Form, Field
  },
  setup () {
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    // 账号登录：false 短信登录：true
    const isMsgLogin = ref(false)

    // 表单校验的基础内容
    const formData = reactive({
      mobile: '13677777777', // 手机号
      account: 'single', // 用户名
      password: '123456', // 密码
      isAgree: true, // 是否同意
      code: ''
    })
    // 校验规则
    const schema = {
      account: validateForm.account,
      mobile: validateForm.mobile,
      password: validateForm.password,
      code: validateForm.code,
      isAgree: validateForm.isAgree
    }

    // 使用倒计时函数
    const { time, start } = useCountDown()
    // 发送验证码
    const sendCode = async () => {
      if (!validateForm.mobile(formData.mobile)) {
        Message({ type: 'error', text: '手机号格式不正确' })
        return
      }
      try {
        await userMobileLoginMsg(formData.mobile)
        Message({ type: 'success', text: '验证码已发送' })
        start(60)
      } catch (err) {
        console.log(err)
      }
    }

    // 兜底校验
    const target = ref(null)
    const checkForm = () => {
      // Form 组件提供了一个 validate 函数作为整体表单校验，返回的是一个promise
      target.value.validate().then((res) => {
        // console.log('表单校验结果', res)
        if (res) {
          // 做提交动作(校验通过)// 短信登录// 手机号登录
          isMsgLogin.value ? doUserMobielLogin() : doUserAccountLogin()
        }
      })
    }

    // 账号登录
    const doUserAccountLogin = async () => {
      // 调用vuex中的actions方法发送ajax
      try {
        // 需要再vuex中抛出错误，这里才能拿到
        await store.dispatch('user/userAccountLogin', formData)
        // 同步购物车
        await store.dispatch('cart/mergeLocalCart')
        Message({ type: 'success', text: '登录成功' })
        // 跳转到主页
        router.push(route.query.return_url || '/')
      } catch (err) {
        Message({ type: 'error', text: '密码或用户名错误' })
      }
    }
    // 手机号登录
    const doUserMobielLogin = async () => {
      // 调用vuex中的actions方法发送ajax
      try {
        // 需要再vuex中抛出错误，这里才能拿到
        await store.dispatch('user/userMobileLogin', formData)
        // 同步购物车
        await store.dispatch('cart/mergeLocalCart')
        Message({ type: 'success', text: '登录成功' })
        // 跳转到主页
        router.push('/')
      } catch (err) {
        Message({ type: 'error', text: '手机号或验证码错误' })
      }
    }

    return { isMsgLogin, formData, schema, checkForm, target, sendCode, time }
  }
}
</script>

<style lang="less" scoped>
// 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: @xtxColor;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: @priceColor;
          }
          &.active,
          &:focus {
            border-color: @xtxColor;
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>
